// pages/registration/longvisitor.js
var Constant = require('../../utils/constant.js');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  
  data: {
    photoPath: '/images/img_add.png',
    roleList: ['业主配偶','业主父母', '业主兄弟', "业主子女", "业主亲戚", "其他"],
    role: '业主配偶',
    userName: '',
    imageSelect: false,
    picBase64: '',
    idCard: '',
    check:'',
    isShowShare: true,

    localLists: [],
    localvalue: '',
    localName: "请选择",
    userOrgCodelList:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.openid){
      app.globalData.openid = options.openid;
      this.setData({
        isShowShare: false,
      })
    }

    //如果在某小区已经是亲属应该不能选择该小区
    for (var i = 0; i < app.globalData.userInfoList.length; i++) {
      if (app.globalData.userInfoList[i].personcheck == 'Y' && app.globalData.userInfoList[i].persontype ==1) {
        this.data.localLists.push(app.globalData.userInfoList[i].unitno)
        this.data.userOrgCodelList.push(app.globalData.userInfoList[i].orgCode)
      }  
    }

    this.setData({
      // localName : this.data.localLists[0],
      localLists: this.data.localLists,
      userOrgCodelList: this.data.userOrgCodelList
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    var pages = getCurrentPages();
    var currPage = pages[pages.length - 1];
    if (currPage.data.photoPath != "/images/img_add.png") {
      that.setData({
        photoPath: currPage.data.photoPath,
        imageSelect: currPage.data.imageSelect,
      });
      console.log(that.data.photoPath)
      picToBase64(that.data.photoPath, this)
    }

    //业主邀请亲属注册
    wx.showLoading({
      title: '请稍后',
    })
    wx.request({
      url: Constant.BASEURL + Constant.GET_SHARE_ID,
      method: 'GET',
      success(res) {
        console.log(res.data)
        personId = res.data.id;
        personKey = res.data.key;
        wx.hideLoading();
      },
      fail(res) {
        console.log("系统错误")
        wx.showToast({
          title: '请检查网络',
          icon: 'none'
        })
        wx.hideLoading();
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },


  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '分享给亲属注册',
      path: 'pages/registration/sharetovisitor?openid=' + app.globalData.openid + "&userType=longvisitor" + "&location=" + app.globalData.unitno + "&personId=" + personId + "&personKey=" + personKey + "&localLists=" + this.data.localLists + "&userOrgCodelList=" + this.data.userOrgCodelList,
      imageUrl: "images/img_city_1.png",
      success(e) {
        wx.showShareMenu({
          withShareTicket: true
        });
      },
      faild(e) {
        console.log(e)
      }
    }
    
  },

  radioChange:function(e){
    console.log(e.detail.value)
    this.setData({
      check:e.detail.value
    })
  },
  idCard: function (e) {
    // console.log(e.detail.value)
    this.setData({
      idCard: e.detail.value
    })
  },
  userName: function(e){
    this.setData({
      userName: e.detail.value,
    })
  },
  bindRoleChange: function (e) {
    this.setData({
      role: this.data.roleList[e.detail.value],
    })
  },
  bindCommunityChange: function (e) {
    this.setData({
      localName: this.data.localLists[e.detail.value],
      localvalue: e.detail.value
    })
  },
  takePicture: function (e) {
    var that = this;
    wx.showActionSheet({
      itemList: ["拍照", "从相册中选择"],
      success: function (res) {
        console.log(res.tapIndex)
        if (res.tapIndex == 0) {
          wx.navigateTo({
            //relation
            url: '../takephoto/takephoto?takePicType=visitor'
          })
        } else {
        
          wx.chooseImage({
            count: 1,
            sourceType: ['album'],
            sizeType: 'compressed',
            success: function (res) {
              var picPath = res.tempFilePaths[0];
              console.log(picPath);

              let manager = wx.getFileSystemManager();
              manager.readFile({
                filePath: picPath,
                encoding: 'base64',
                success: function (res) {
                  //console.log(res.data)
                  that.data.picBase64 = res.data;
                  // setTimeout(function () {

                  // }, 500);
                  wx.showLoading({
                    title: '检测中',
                  })
                  
                  wx.request({
                    url: Constant.BASEURL + Constant.PICDETECT_URL,
                    method: 'POST',
                    data: { "personphoto": that.data.picBase64 },
                    success: function (res) {
                      var retCode = res.data.obj;
                      if (retCode == "0") {
                        that.setData({
                          photoPath: picPath,
                          imageSelect: true,
                        });
                      } else {

                        let state_msg = "";
                        if (retCode == Constant.STATE_ERROR_FILE_TYPE) {
                          state_msg = '网络请求错误';
                        } else if (retCode == Constant.STATE_ERROR_FILE_INCOMPLETE) {
                          state_msg = '发送的数据不完整，请检查网络连接';
                        } else if (retCode == Constant.STATE_ERROR_FILE_DATA) {
                          state_msg = '不能解析图像数据';
                        } else if (retCode == Constant.STATE_ERROR_FACE_NUM) {
                          state_msg = '人脸数量不正确，请重新选择';
                        } else if (retCode == Constant.STATE_ERROR_FACE_YIN_YANG) {
                          state_msg = '光线不均匀，请重新选择';
                        } else if (retCode == Constant.STATE_ERROR_FACE_BORDER) {
                          state_msg = '请将人脸放在画面中央';
                        } else if (retCode == Constant.STATE_ERROR_FACE_RESOLUTION) {
                          state_msg = '人脸太小，请重新选择';
                        } else if (retCode == Constant.STATE_ERROR_FACE_ANGLE) {
                          state_msg = '人脸角度偏差太大，请重新选择';
                        } else if (retCode == Constant.STATE_ERROR_IMAGE_QUALITY) {
                          state_msg = '图像质量太差';
                        } else {
                          state_msg = '未知错误，错误码' + retCode;
                        }
                      
                        wx.showModal({
                          title: '提示',
                          content: state_msg,
                          showCancel: false,
                          success: function (res) { },
                        })
                      }
                      wx.hideLoading();
                    },
                    fail: function (res) {
                      wx.hideLoading();
                      wx.showToast({
                        title: '请检测网络连接',
                        icon: 'none'
                      })
                    }
                  })
                },
                fail: function (res) {
                  console.log(res)
                  wx.showModal({
                    title: '提示',
                    content: '照片无效，请重新选择',
                    showCancel: false,
                    success: function (res) { },
                  })
                }
              })
            },
          })

        }
      }
    })
    
  },
  buttonAdd: function (e){
    var that = this;
    // console.log(that.data.userName)
    // console.log(that.data.role)

    if (that.data.userName == '') {
      wx.showToast({
        title: '请填写姓名',
        icon: 'none',
      })
      return;
    }

    if(that.data.idCard != ""){
      console.log(Constant.idCard(that.data.idCard))
      if(!Constant.idCard(that.data.idCard)){
        wx.showToast({
          title: '身份证不正确',
          icon: 'none',
        })
        return;
      }
      
    }else{
      wx.showToast({
        title: '身份证号为必填项',
        icon: 'none',
      })
      return;
    }

    // console.log("小区", this.data.localName);

    if (this.data.localName == ''){
      wx.showToast({
        title: '请选择小区',
        icon: 'none',
      })
      return;
    }

    if(that.data.photoPath == "/images/img_add.png"){
      wx.showToast({
        title: '需要上传照片',
        icon: 'none',
      })
      return;
    }

    wx.showLoading({
      title: '添加中',
    })
    
    wx.request({
      url: Constant.BASEURL + Constant.LONG_USER_URL,
      method:'POST',
      data: { "personname": that.data.userName, "personrelation": that.data.role, "personidcardno": that.data.idCard, "childcheck": that.data.check, "personphoto": that.data.picBase64, "openid": app.globalData.openid, "unitno": that.data.userOrgCodelList[this.data.localvalue]},
      success: function(res){
        console.log(res.data)
        wx.hideLoading();
        if(res.data.respCode == "0"){
          wx.showModal({
            title: '添加成功',
            content: "添加亲属成功",
            showCancel: false,
            success: function(res){
              wx.navigateBack({
                delta:2,
              })
            }
          })
        }else{
          wx.showModal({
            title: '添加失败',
            content: res.data.data,
            showCancel: false,
          })
        }
      },
      fail: function(res){
        wx.hideLoading();
        wx.showModal({
          title: '系统错误',
          content: res.data.data,
          showCancel: false,
        })
      }
    })
  }
})

var personId = "";
var personKey = "";
function picToBase64(path, that) {
  let manager = wx.getFileSystemManager();
  manager.readFile({
    filePath: path,
    encoding: 'base64',
    success: function (res) {
      console.log("编码base64成功")
      that.data.picBase64 = res.data;
    },
    fail: function (res) {
      console.log(res)
    }
  })
}